import { PageLoading } from '@ant-design/pro-layout';
import React, { useEffect, useState } from 'react';
import { connect, Redirect } from 'umi';
import { stringify } from 'querystring';
import { Button, Modal } from 'antd';
import { ExclamationCircleOutlined } from '@ant-design/icons';

const SessionTimeoutModal = ({ visible, onOK, onCancel }) => (
  <Modal
    title={null}
    footer={null}
    closable={false}
    width={416}
    visible={visible}
    className="ant-modal-confirm ant-modal-confirm-confirm"
  >
    <div className="ant-modal-confirm-body-wrapper">
      <div className="ant-modal-confirm-body">
        <ExclamationCircleOutlined style={{ color: '#1890ff' }} />
        <span className="ant-modal-confirm-title">提示</span>
        <div className="ant-modal-confirm-content">会话超时，请重新登录!!</div>
      </div>
      <div className="ant-modal-confirm-btns">
        <Button onClick={onCancel}>取消</Button>
        <Button onClick={onOK} type="primary">
          确认
        </Button>
      </div>
    </div>
  </Modal>
);

const BasicLayout = (props) => {
  const { children, login, loading, dispatch } = props;

  const [isReady, setReady] = useState(false);

  useEffect(() => {
    setReady(true);
    dispatch({
      type: 'login/fetchLoginUser',
    });
  }, []);

  if (loading || !isReady) {
    return <PageLoading />;
  }

  const { loginUser } = login;

  if (!loginUser) {
    const queryString = stringify({ redirect: window.location.href });
    return <Redirect to={`/login?${queryString}`} />;
  }

  const onOK = () => {
    dispatch({ type: 'login/logout' });
  };

  const onCancel = () => {
    dispatch({
      type: 'login/sessionTimeout',
      payload: { sessionTimeout: false },
    });
  };

  return (
    <>
      {children}
      <SessionTimeoutModal visible={!!loginUser.sessionTimeout} onOK={onOK} onCancel={onCancel} />
    </>
  );
};

export default connect(({ loading, login }) => ({
  login,
  loading: loading.effects['login/fetchLoginUser'],
}))(BasicLayout);
